package org.coursera.codebreak;

public class FrequencyArray {
	
	private int k;
	private byte[] f;
	
	public static void main(String[] args) {
		FrequencyArray fa = FrequencyArray.getInstance(5);
		//System.out.println(fa.patternToNumber("AAAAT"));
		System.out.println(fa.patternToNumber("TTTTT"));
		//System.out.println(fa.numberToPattern(0));
		System.out.println(fa.numberToPattern(1023));
	}
	
	private FrequencyArray() {}
	private FrequencyArray(int k) {
		this.k = k;
		this.f = new byte[Double.valueOf(Math.pow(4, k)).intValue()];
	}
	
	public static FrequencyArray getInstance(int k) {
		return new FrequencyArray(k);
	}
	
	private int patternToNumber(String pattern) {
		int arrayIndex = 0;
		int tmax = k - 1;
		for (int i=0; i<k; i++) {
			switch (pattern.charAt(i)) {
				case 'A' : break; //arrayIndex+=0*Math.pow(4, tmax-i); break;
				case 'C' : arrayIndex+=1*Math.pow(4, tmax-i); break;
				case 'G' : arrayIndex+=2*Math.pow(4, tmax-i); break;
				case 'T' : arrayIndex+=3*Math.pow(4, tmax-i); break;
			}
		}
				
		return arrayIndex;
	}
	
	public String numberToPattern(int arrayIndex) {
		StringBuffer sb = new StringBuffer();
		int tmax = k - 1;
		for (int i=tmax; i>=0; i--) {
			int divisor = Double.valueOf(Math.pow(4, i)).intValue();
			switch (arrayIndex/divisor) {
				case 0 : sb.append('A'); break;
				case 1 : sb.append('C'); break;
				case 2 : sb.append('G'); break;
				case 3 : sb.append('T'); break;				
			}			
			arrayIndex%=divisor;
		}				
		return sb.toString();
	}
	
	public byte[] computingFrequencies(String gnomeSlice) {		
		for (int i=0; i<=gnomeSlice.length()-k; i++) {
			String pattern = gnomeSlice.substring(i, i+k);
			f[patternToNumber(pattern)]++;
		}		
		return f;
	}
	
	public void reset() {
		for (int i=0;i<f.length;i++) {
			f[i]=0;
		}
	}
}
